<?php

/**
 * @Author: kendy
 * @Date:   2020-02-21 10:44:39
 * @Last Modified by:   jiayanting
 * @Last Modified time: 2020-02-28 16:49:58
 */  
namespace app\common\model;
use think\Model;
use think\Db;
use think\Loader;
use app\common\model\LogOrderModel as lo;
class JlouOrderModel extends Model
{
    // 确定链接表名
    protected $name = 'jlou_order';
    /**
     * 根据搜索条件获取所有的捡漏订单数据
     * @param $where  查询条件
     * @param $offset
     * @param $limit
     * @return mixed
     */
    public function submitJlOrder()
    {  
     $goods_id = input('post.goods_id');
     $address = input('post.address');
     $phone = input('post.phone');
     $name = input('post.name'); 
     $userId = input('post.uid');
     $payType = input('post.pay_type');//支付类型1支付宝，2微信
     if(empty($goods_id))
        return apiReturn('400','商品id为空',0);
     if(empty($address))
        return apiReturn('400','收货人地址为空',0);
     if(empty($phone))
        return apiReturn('400','收货人电话',0);
     if(empty($name))
        return apiReturn('400','收货人姓名为空',0);
    if(empty($userId))
        return apiReturn('400','用户信息为空',0);
     if(empty($payType))
        return apiReturn('400','支付类型为空',0);
     //查看是否有该门票
     $goodsInfo = Db::name('jlou_goods')  
     ->where(['id'=>$goods_id,'is_del'=>0,'is_display'=>1])
     ->find();
     if(empty($goodsInfo)) return apiReturn('400','购买的商品信息为空',0);
     if(time()>strtotime($goodsInfo['time'])){ 
          return apiReturn('400','购买的商品已过期',0);
     }
      //生成订单
      Db::startTrans();
      try{ 
        $orderSn = makeOrderSn();  
      //创建订单    
        $order['order_sn'] = $orderSn; 
        $order['uid'] = $userId;
        $order['goods_id'] = $goods_id;
        $order['name'] = $name;
        $order['address'] = $address;
        $order['phone'] = $phone;
        $order['order_status'] =  0;
        $order['order_price'] =  $goodsInfo['shop_price']; 
        $order['create_time'] =  date('Y-m-d H:i:s',time()); 
        $result = $this->isUpdate(false)->save($order); 
        if(false !== $result)
        { 
           //创建订单记录
            $orderId = $this->order_id; 
            $logOrder = new lo();
            $logOrder->addLogOrder($orderId,4, $userId, 0, '下单成功，等待用户支付');
            //吊起支付宝或是微信支付
             if($payType == 1){
                //调起支付宝接口
              $data =  $this->getAlipays($this->order_sn,$userId,4,$goodsInfo['shop_price']);
             }
             if($payType ==2){
             	//调起微信支付
             	$data = $this->getWxpays($this->order_sn,4,$userId,$goodsInfo['shop_price']);
             } 
        } 
        Db::commit();
      //  return apiReturn('200','提交订单成功',$data);  
      }catch(\Exception $e){
        Db::rollback();
        return apiReturn('400', $e->getMessage(),0); 
      }

   }
    public function getAlipays($order_sn,$uid,$order_type,$order_price)//订单类型 订单类型 1酒店，2景点，3跟团 
    {
        Loader::import('Alipay.aop.AopClient');
        $aop = new \AopClient();

        $config = config('alipay');
        $aop->gatewayUrl = $config['gatewayUrl'];
        $aop->appId = $config['appId'];
        $aop->rsaPrivateKey = $config['rsaPrivateKey'];
        $aop->format = $config['format'];
        $aop->postCharset = $config['postCharset'];
        $aop->signType = $config['signType'];
        $aop->alipayrsaPublicKey = $config['alipayrsaPublicKey'];

        Loader::import('Alipay.aop.request.AlipayTradeAppPayRequest');

        $request = new \AlipayTradeAppPayRequest(); 
        $passback_params = $uid."@".$order_type;
        $bizcontentArr= array(
            'subject'=>'支付购买商品费用'.$order_price.'元',
            'out_trade_no'=>$order_sn,
            'total_amount'=>$order_price,
            'passback_params'=>UrlEncode($passback_params),
            'product_code'=>'QUICK_MSECURITY_PAY'
        ); 
        $request->setNotifyUrl('http://api.lancly.com/api/Alipays/aliNotify');
        $bizcontent = json_encode($bizcontentArr);
        $request->setBizContent($bizcontent);
        $response = $aop->sdkExecute($request); 
        return apiReturn('200','请求成功',$response); 

    }
     public function getWxpays($order_sn,$order_type,$uid,$order_price)
    { 
        //微信支付
        Loader::import('WxPay.WxPay',EXTEND_PATH,'.Api.php');
        $config = new \WxPayConfig();
        $WxPay  = new \WxPayApi();
        $WxData = new \WxPayUnifiedOrder();  
        $passback_params = base64_encode($uid."@".$order_type);
        $dataArr = array(
            'out_trade_no'     => $order_sn,            //订单号
            'body'             => '支付购买商品费用'.$order_price.'元',                         //商品名
            'total_fee'        => $order_price * 100,        //支付总金额
            'trade_type'       => 'APP',                     //支付途径
            'nonce_str'        => $WxPay->getNonceStr(),    //32位随进数
            'notify_url'       => 'http://api.lancly.com/api/Wxpays/aliNotify',// 异步通通知地址
            'spbill_create_ip' => $_SERVER['REMOTE_ADDR'],
            'attach'           => $passback_params
        ); 
        $WxData->SetOut_trade_no($dataArr['out_trade_no']);
        $WxData->SetBody($dataArr['body']);
        $WxData->SetTotal_fee($dataArr['total_fee']);
        $WxData->SetTrade_type($dataArr['trade_type']);
        $WxData->SetNonce_str($dataArr['nonce_str']);
        $WxData->SetAttach($dataArr['attach']);
        $WxData->SetNotify_url($dataArr['notify_url']);
        $WxData->SetSpbill_create_ip($dataArr['spbill_create_ip']);
        $WxData->SetSign($config);
        $return = $WxPay->unifiedOrder($config,$WxData); 
        if (array_key_exists('result_code',$return) && array_key_exists('return_code',$return) && $return['result_code'] == 'SUCCESS' && $return['return_code'] == 'SUCCESS'){
            $signArr = array(
                'appid'     =>$config->GetAppId(),
                'partnerid' =>$config->GetMerchantId(),
                'timestamp' =>time(),
                'package'   =>'Sign=WXPay',
                'noncestr'  =>$return['nonce_str'],
                'prepayid'  =>$return['prepay_id']
            );
            $setSignClass = new \WxPayResults();
            $setSignClass->SetData('sign',$return['sign']);
            $setSignClass->SetData('appid',$signArr['appid']);
            $setSignClass->SetData('partnerid',$signArr['partnerid']);
            $setSignClass->SetData('timestamp',$signArr['timestamp']);
            $setSignClass->SetData('package',$signArr['package']);
            $setSignClass->SetData('noncestr',$signArr['noncestr']);
            $setSignClass->SetData('prepayid',$signArr['prepayid']);
            $signToApp = $setSignClass->MakeSign($config);  
            $response = array('prepay_id'=>$return['prepay_id'],'sign'=>$signToApp,'timestamp'=>$signArr['timestamp'],'noncestr'=>$signArr['noncestr']); 
             return apiReturn('200','请求成功',$response); 
        }else{ 
        	  return apiReturn('401','提交失败',0);  
        }

    }
      
 } 